package com.example.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    private static DataSource ds;
    private  static Connection conn;
    static{
        try {
        // 获取加载配置文件的对象
        Properties properties = new Properties();
        // 获取类的类加载器
        ClassLoader classLoader = DruidUtils.class.getClassLoader();
        // 获取druid-1.2.8.properties配置文件资源输入流
        InputStream inputStream = classLoader.getResourceAsStream("druid.properties");
        // 加载配置文件
        properties.load(inputStream);
        // 获取连接池对象
         ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

    /**
     * 获取连接池对象
     * @return
     */
    public static DataSource getDataSource(){
        return ds;
    }
    /**
     * 获取数据库连接对象
     * @return
     */
    public static Connection getConnection(){
        try {
            conn = ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

}
